package com.xh.clean.modular.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xh.clean.core.cache.CacheKit;
import com.xh.clean.core.common.constant.cache.Cache;
import com.xh.clean.core.common.constant.cache.CacheKey;
import com.xh.clean.core.common.exception.BizExceptionEnum;
import com.xh.clean.core.exception.CleanException;
import com.xh.clean.core.support.StrKit;
import com.xh.clean.modular.system.dao.DictMapper;
import com.xh.clean.modular.system.model.Dict;
import com.xh.clean.modular.system.service.IDictService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import static com.xh.clean.core.common.constant.factory.MutiStrFactory.*;

@Service
@Transactional
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements IDictService {

    @Resource
    private DictMapper dictMapper;

    @Override
    public void addDict(String dictName, String dictValues) {
        //判断有没有该字典
        List<Dict> dicts = dictMapper.selectList(new EntityWrapper<Dict>().eq("name", dictName).and().eq("pid", 0));
        if (dicts != null && dicts.size() > 0) {
            throw new CleanException(BizExceptionEnum.DICT_EXISTED);
        }

        //解析dictValues
        List<Map<String, String>> items = parseKeyValue(dictValues);

        //添加字典
        Dict dict = new Dict();
        dict.setName(dictName);
        dict.setNum(0);
        dict.setPid(0);
        this.dictMapper.insert(dict);

        //添加字典条目
        for (Map<String, String> item : items) {
            String num = item.get(MUTI_STR_KEY);
            String name = item.get(MUTI_STR_VALUE);
            Dict itemDict = new Dict();
            itemDict.setPid(dict.getId());
            itemDict.setName(name);
            try {
                itemDict.setNum(Integer.valueOf(num));
            } catch (NumberFormatException e) {
                throw new CleanException(BizExceptionEnum.DICT_MUST_BE_NUMBER);
            }
            this.dictMapper.insert(itemDict);
        }
    }

    @Override
    public void editDict(Integer dictId, String dictName, String revmoveIds, String subDictsValues) {
        //判断有没有该字典
        Dict dict = new Dict();
        dict.setId(dictId);
        dict.setPid(0);
        Dict mainDict = dictMapper.selectOne(dict);
        if (mainDict != null) {
            mainDict.setName(dictName);
            dictMapper.updateById(mainDict);
            CacheKit.remove(Cache.CONSTANT, CacheKey.DICT_NAME + dictId);
        }
        //解析dictValues
        List<Map<String, String>> items = parseKeyValue(subDictsValues);
        List<Dict> dicts = dictMapper.selectList(new EntityWrapper<Dict>().eq("pid", dictId));
        for (int i = 0; i < items.size(); i++) {
            List<Dict> isExist = dictMapper.selectList(new EntityWrapper<Dict>().eq("num", Integer.parseInt(items.get(i).get("KEY"))).eq("pid", dictId));
            if (isExist.size() > 0) {
                dicts.get(i).setNum(Integer.parseInt(items.get(i).get("KEY")));
                dicts.get(i).setName(items.get(i).get("VALUE"));
                dictMapper.updateById(dicts.get(i));
                CacheKit.remove(Cache.CONSTANT, CacheKey.DICT_NAME + dicts.get(i).getId());
            } else {
                Dict itemDict = new Dict();
                itemDict.setPid(dictId);
                itemDict.setName(items.get(i).get("VALUE"));
                itemDict.setNum(Integer.parseInt(items.get(i).get("KEY")));
                dictMapper.insert(itemDict);
            }
        }
        if (StrKit.isNotEmpty(revmoveIds)) {
            revmoveIds = StrKit.removeSuffix(revmoveIds, StrKit.COMMA);
            //删除之前的字典
            String[] split = revmoveIds.split(",");
            for (String removeId : split) {
                this.delteDict(Integer.valueOf(removeId));
                CacheKit.remove(Cache.CONSTANT, CacheKey.DICT_NAME + removeId);
            }
        }
    }

    @Override
    public void delteDict(Integer dictId) {
        //删除这个字典的子词典
        Wrapper<Dict> dictEntityWrapper = new EntityWrapper<>();
        dictEntityWrapper = dictEntityWrapper.eq("pid", dictId);
        dictMapper.delete(dictEntityWrapper);

        //删除这个词典
        dictMapper.deleteById(dictId);
    }

    @Override
    public List<Dict> selectByCode(String code) {
        return this.baseMapper.selectByCode(code);
    }

    @Override
    public List<Map<String, Object>> list(String conditiion) {
        return this.baseMapper.list(conditiion);
    }

    @Override
    public List<Map<String, Object>> selectByPid(Integer pid) {
        return this.baseMapper.selectByPid(pid);
    }

    @Override
    public List<Map<String, Object>> selectByPidAndIdNotIn(Integer patrolAreaPid, List<String> list) {
        Wrapper<Dict> dictWrapper = new EntityWrapper<Dict>().eq("pid", patrolAreaPid);
        if (list != null) {
            dictWrapper.and().notIn("id", list);
        }
        return dictMapper.selectMaps(dictWrapper);
    }

    @Override
    public List<Map<String, Object>> selectByInId(List<String> list) {
        return dictMapper.selectMaps(new EntityWrapper<Dict>().in("id", list));
    }
}
